﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Steamrunner
{
    class ScreenManager : DrawableGameComponent
    {
        SpriteBatch spriteBatch = null;
        InputManager inputManager = null;

        public Dictionary<string, Screen> screens = new Dictionary<string, Screen>();
        Screen currentScreen = null;

        public SpriteBatch SpriteBatch
        {
            get { return spriteBatch; }
        }

        public InputManager InputManager
        {
            get { return inputManager; }
        }

        public string CurrentScreen
        {
            set
            {
                if (currentScreen != null)
                {
                    currentScreen = screens[currentScreen.GetNextScreen()];
                    if (currentScreen == null)
                    {
                        Game.Exit();
                    }
                    else
                    {
                        currentScreen.Initialize();
                    }
                }
                else
                {
                    screens.TryGetValue(value, out currentScreen);
                    if (currentScreen == null)
                    {
                        Game.Exit();
                    }
                    else
                    {
                        currentScreen.Initialize();
                    }
                }
            }
        }

        public ScreenManager(Game game)
            : base(game)
        {
        }

        public override void Initialize()
        {
            inputManager = new InputManager(Game);

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            if (currentScreen != null)
            {
                currentScreen.Update(gameTime);
            }
            
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            if (currentScreen != null)
            {
                currentScreen.Draw(gameTime);
            }
            
            base.Draw(gameTime);
        }

        public void AddScreen(string id, Screen screen)
        {
            screens.Add(id, screen);
        }

        public void RemoveScreen(string id)
        {
            Screen screen = screens[id];
            if (screen != null)
            {
                screen.Dispose();
                screens.Remove(id);
            }
        }
    }
}
